package com.biz.ssm.security;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class SecurityContextUtils {

	private static Logger logger = LoggerFactory.getLogger(SecurityContextUtils.class);

	public static MyUserDetails getCurrentUser(){
		MyUserDetails userDetails = null;
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if(null != auth && auth instanceof MyAuthenticationJWTToken){
			userDetails = (MyUserDetails)auth.getPrincipal();
		}
		return userDetails;
	}

	public static <T> T getCurrentUser(Class<T> claz){
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if(null != auth && auth instanceof MyAuthenticationJWTToken){
			MyUserDetails userDetails = (MyUserDetails)auth.getPrincipal();
			if(null != userDetails && null != userDetails.getExtraParam()){
				return JSON.parseObject(userDetails.getExtraParam().toJSONString(), claz);
			}
		}
		return null;
	}



	public static String getIpAddress() {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
	    String ip = request.getHeader("x-forwarded-for");
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	        ip = request.getHeader("Proxy-Client-IP");
	    }
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	        ip = request.getHeader("WL-Proxy-Client-IP");
	    }
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	        ip = request.getRemoteAddr();
	    }
	    if (ip.contains(",")) {
	        return ip.split(",")[0];
	    } else {
	        return ip;
	    }
	}
}
